﻿using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace Wangzeran.CodeMaker.PlugIns.Util
{
    /// <summary>
    /// Python脚本引擎
    /// </summary>
    public class PythonScriptEngine
    {
        /// <summary>
        /// 脚本引擎
        /// </summary>
        private static ScriptEngine scriptEngine;
        /// <summary>
        /// 脚本引擎
        /// </summary>
        public static ScriptEngine ScriptEngine
        {
            get
            {
                if (scriptEngine == null)
                {
                    scriptEngine = Python.CreateEngine();
                }
                return scriptEngine;
            }
        }

        private ScriptScope scriptScope = null;
        /// <summary>
        /// 脚本范围
        /// </summary>
        public ScriptScope ScriptScope
        {
            get
            {
                if (scriptScope == null)
                {
                    scriptScope = CreateNewScriptScope();
                }
                return scriptScope;
            }
        }

        private ScriptScope resultScriptScope = null;
        /// <summary>
        /// 结果脚本
        /// </summary>
        public ScriptScope ResultScriptScope
        {
            get { return resultScriptScope; }
            set { resultScriptScope = value; }
        }


        /// <summary>
        /// 创建新的脚本范围
        /// </summary>
        /// <returns></returns>
        private static ScriptScope CreateNewScriptScope()
        {
            return ScriptEngine.CreateScope();
        }


        /// <summary>
        /// 添加脚本变量
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public void AddVariable(string key, string value)
        {
            ScriptEngine.SetVariable(ScriptScope, key, value);
        }

        /// <summary>
        /// 获取脚本变量
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public object GetVariable(string key)
        {
            return ResultScriptScope.GetVariable(key);
        }

        /// <summary>
        /// 执行脚本文件
        /// </summary>
        /// <param name="path">文件路径</param>
        public void ExecuteFile(string path)
        {
            ResultScriptScope = ScriptEngine.ExecuteFile(path, ScriptScope);
        }

    }
}
